<template>
   <div class="w-full h-screen box-border relative overflow-x-hidden overflow-y-auto">
      <div class="w-full h-[28vh] home-bg box-border p-8">
      </div>
     <div class="flex flex-col justify-start items-center box-border p-2">
         <van-button color="linear-gradient(-90deg, #a147ff, #f52a2a)" round class="!text-yellow-500 text-[18px]">
            <span class="mr-1">{{ $t('stage') }}</span>
            <span>{{ current?.periodNo }}</span>
         </van-button>
         <div class="w-full flex flex-row justify-between items-center mt-2 text-[16px] font-bold box-border px-6">
            <div>
               <span>{{ $t('endInvolved') }}</span>
               <span>:</span>
               <span class="text-red-600 ml-2">
                  {{ startTime }}
               </span>
            </div>
            <div>
               <span>{{ $t('endLottery') }}</span>
               <span>:</span>
               <span class="text-red-600 ml-2">
                  {{ endTime }}
               </span>
            </div>
         </div>
     </div>
     <div class="box-border px-2 bg-white mb-16">
      <div class="bg-[#f1f6fe] box-border p-2 flex flex-col justify-start items-center mb-2" v-for="(item, i) in list">
         <div class="w-full flex justify-between items-center">
            <div class="text-[15px]">
               <span class="mr-1 text-[18px] font-semibold text-red-500">
                  {{ item.tableId }}
               </span>
               <span>{{ $t('lowMoney') }}</span>
               <span class="mr-2">:</span>
               <span>{{ item.minMoney }}</span>
            </div>
            <div class="text-[#878b99] text-[14px]">
               {{ moment(item.bluePropaganda.createTime || '').format('YYYY-MM-DD HH:mm:ss') }}
            </div>
         </div>
         <div class="flex justify-between items-start gap-6">
            <div class="max-sm:w-[9.8rem] h-6 w-full text-ellipsis overflow-hidden whitespace-nowrap text-[16px]">
               {{ item.redPropaganda[activeLang] || item.redPropaganda.title }}
            </div>
            <div class="max-sm:w-[9.8rem] h-6 w-full text-ellipsis overflow-hidden whitespace-nowrap text-[16px]">
               {{ item.bluePropaganda[activeLang] || item.bluePropaganda.title }}
            </div>
         </div>
         <div class="w-full flex justify-between items-center mt-2 relative overflow-hidden">
            <div class="flex-1 flex justify-center items-center red-team box-border pl-4 pr-6 py-6">
               <van-button round block @click="openPopup('red', item)" class="!border-none">
                  <div class="text-red-500 text-[15px] font-semibold">
                     {{ $t('selectRed') }}
                  </div>
               </van-button>
            </div>
            <div class="flex-1 flex justify-center items-center blue-team box-border pl-6 pr-4 py-6">
               <van-button round block class="!border-none" @click="openPopup('blue', item)" >
                  <div class="text-blue-500 text-[15px] font-semibold">
                     {{ $t('selectBlue') }}
                  </div>
               </van-button>
            </div>
         </div>
      </div>
     </div>
     <van-popup v-model:show="show" round class="box-border w-full pt-2 pb-6 px-4">
      <div class="text-[18px] text-center mb-6">
         {{ $t('rank', [selectData.tableId]) }}
      </div>
      <van-icon
        name="close" 
        color="#969799" 
        size="1.4rem" 
        class="absolute right-2 top-2 clear-both" 
        @click="closePopup()"
      />
      <van-form @submit="submit" ref="formRef">
         <div class="flex justify-center items-center gap-10">
            <van-button 
               size="small" 
               :type="activeRed ? 'danger' : 'default'" 
               block 
               round 
               @click="changActiveTeam()"
            >
               <span>{{ $t('redTeam') }}</span>
            </van-button>
            <van-button 
               size="small" 
               block 
               round  
               @click="changActiveTeam()" 
               :type="activeBlue ? 'primary' : 'default'"
            >
               <span>{{ $t('blueTeam') }}</span>
            </van-button>
         </div>
         <div class="flex flex-col justify-center items-center gap-3 my-3 text-[#969799]">
            <div class="flex justify-center items-center text-[14px]">
               <span>{{ $t('balance') }}</span>
               <span class="mr-2">:</span>
               <span class="text-black">
                  {{ balance }}
               </span>
               <span>{{ $t('currency') }}</span>
            </div>
            <div class="flex justify-center items-center text-[14px]" v-show="activeRed">
               <span>{{ $t('redTeamOdds') }}</span>
               <span class="mr-2">:</span>
               <span class="text-black">
                  {{ selectData.oddsRed || '-' }}
               </span>
            </div>
            <div class="flex justify-center items-center text-[14px]" v-show="activeBlue">
               <span>{{ $t('blueTeamOdds') }}</span>
               <span class="mr-2">:</span>
               <span class="text-black">
                  {{ selectData.oddsBlue || '-' }}
               </span>
            </div>
            <div class="flex justify-center items-center">  
               <van-stepper 
                  v-model="count" 
                  input-width="140px" 
                  button-size="36px"
                  integer 
                  :min="selectData.minMoney || 1"
                  :max="selectData.maxMoney || ''"
               />
               <span class="ml-2 text-black">
                  {{ $t('currency') }}
               </span>
            </div>
            <div class="flex justify-center items-center gap-2">
               <van-button 
                  block 
                  :color="activePrice === '100000' ? '#f6ad4a' : '#eee'" @click="changActivePrice('100000')"
               >
                  <span 
                     class="text-[13px]" 
                     :class="activePrice === '100000' ? 'text-white' : 'text-[#b0b3bf]'"
                  >
                     100000
                  </span>
               </van-button>
               <van-button
                  block 
                  :color="activePrice === '50000' ? '#f6ad4a' : '#eee'" 
                  @click="changActivePrice('50000')"
               >
                  <span 
                     class="text-[13px]" 
                     :class="activePrice === '50000' ? 'text-white' : 'text-[#b0b3bf]'"
                  >
                     50000
                  </span>
               </van-button>
               <van-button 
                  block 
                  :color="activePrice === 'all' ? '#f6ad4a' : '#eee'" 
                  @click="changActivePrice('all')"
               >
                  <span 
                     class="text-[13px]" 
                     :class="activePrice === 'all' ? 'text-white' : 'text-[#b0b3bf]'"
                  >
                     {{ $t('all') }}
                  </span>
               </van-button>
               <van-button block color="#eee" @click="closePopup()">
                  <span class="text-[13px] text-[#b0b3bf]">
                     {{ $t('btnText.cancel') }}
                  </span>
               </van-button>
            </div>
         </div>
         <div class="mt-12">
            <van-button 
               round 
               block 
               type="primary" 
               native-type="submit" 
               color="linear-gradient(-90deg, #ff5b3b, #ffa439)"
               :loading="loading"
            >
               <span class="text-white text-[14px]">
               {{ $t('btnText.joinNow') }}
               </span>
            </van-button>
         </div>
      </van-form>
     </van-popup>
   </div>
</template>
<script setup lang="ts">
import { showToast, type FormInstance } from "vant"

import { useI18n } from 'vue-i18n'

import { useUserStore } from "@/store/user"

import moment from "moment"

import Decimal from "decimal.js"

import { periodItem, createOrder } from "@/service/login"

const user = useUserStore()

const { t } =  useI18n({ useScope: 'global' })

const activeLang = computed(() => user.lang.split('-')[0])

onBeforeMount(() => user.loadWallet())

const balance = computed(() => new Decimal((user?.wallet?.balance || 0)).toFixed(2))

const show = ref<boolean>(false)

const loading = ref<boolean>(false)

const count = ref<string>('0')

const activeRed = ref<boolean>(false)

const activeBlue = ref<boolean>(false)

const activePrice = ref<string>()

const changActiveTeam = () => {
   activeBlue.value = !activeBlue.value
   activeRed.value = !activeRed.value
}

const current = ref<any>()

// const activeIndex = ref<number>()

const selectData = ref<any>()

const startTime = ref<string>()

const getStartTime = () => {
   if(!current.value?.startTime) return 
   const time = moment.duration(moment(current.value?.startTime).diff(moment()))

   const minutes = time.get('minutes') < 10 ? '0' + time.get('minutes') : time.get('minutes')

   const seconds = time.get('seconds') < 10 ? '0' + time.get('seconds') : time.get('seconds')

   if(time.get('seconds') > 0) return startTime.value = `${minutes}:${seconds}`

   startTime.value =  t('sealedDisk')
}

const endTime = ref<string>()

const getEndTime = () => {
   if(!current.value?.endTime) return 
   const time = moment.duration(moment(current.value?.endTime).diff(moment()))

   const minutes = time.get('minutes') < 10 ? '0' + time.get('minutes') : time.get('minutes')

   const seconds = time.get('seconds') < 10 ? '0' + time.get('seconds') : time.get('seconds')

   if(time.get('seconds') > 0) return endTime.value = `${minutes}:${seconds}`

   endTime.value = '00:00'
}

const timer: any = setInterval(() => {
   getEndTime()
   getStartTime()
}, 1000)

onBeforeUnmount(() => clearInterval(timer))

const list = ref<any[]>([])

const getCurrent = async () => {
   const { success, data: { items = [], ...other } } = await periodItem({
      tenantId: '10068'
   })

   if(!success) return 

   current.value = other

   list.value = (items || []).map((v: any) => {
      const redPropaganda = v.redPropaganda?.langList.reduce((p: any, c: any) => {
         return Object.assign(p, { [c.lang]: c.title })
      }, v.redPropaganda)
      const bluePropaganda = v.bluePropaganda?.langList.reduce((p: any, c: any) => {
         return Object.assign(p, { [c.lang]: c.title })
      }, v.bluePropaganda)
      return {
         ...v,
         redPropaganda,
         bluePropaganda
      }
   })
}

onBeforeMount(() => getCurrent())

const changActivePrice = (str: string) => {
   switch(str) {
      case '100000':
         count.value = '100000'
         activePrice.value = str
         break
      case '50000':
         count.value = '50000'
         activePrice.value = str
         break
      case 'all':
         activePrice.value = 'all'
         if(!balance.value) return
         count.value = balance.value
         break
   }
}

const formRef = ref<FormInstance>()

const openPopup = (str: string, data: any) => {
   selectData.value = data
   switch(str){
      case "red":
         show.value = true
         activeRed.value = true
         break
      case "blue":
         show.value = true
         activeBlue.value = true
         break
   }
}

const closePopup = () => {
  formRef.value?.resetValidation()
  show.value = false
  activePrice.value = undefined
  activeBlue.value = false
  activeRed.value = false
}

const submit = async () => {
   try {
      loading.value = true
      const res = await createOrder({
         periodId: selectData.value.periodId,
         money: count.value,
         bet: activeBlue.value ? 'BLUE' : activeRed.value ? 'RED' : '',
         tableId: selectData.value.tableId,
         lang: activeLang.value
      })

      loading.value = false

      if(!res.success) return 

      showToast(res.message)

      closePopup()
   } catch(err){
      loading.value = false
      throw err
   }
}
</script>

<style lang="less" scoped>
.home-bg{
  background: url('@/assets/images/home-bg.png')no-repeat;
  background-size: 100% 100%;
}
.red-team {
  background: url('@/assets/images/red-bg.png')no-repeat;
  background-size: 100% 100%;
}
.red-team::after{
   content: '';
   position: absolute;
   left: 50%;
   top: 50%;
   width: 2.6rem;
   height: 2.62rem;
   transform: translate(-50%, -50%);
   background: url('@/assets/images/pk.png')no-repeat;
   background-size: 100% 100%;
}
.blue-team {
  background: url('@/assets/images/blue-bg.png')no-repeat;
  background-size: 100% 100%;
}
</style>
